import axios, { AxiosRequestConfig } from 'axios'

//设置axios配置和拦截器
axios.defaults.baseURL = ''
axios.defaults.timeout = 60 * 1000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// 请求拦截
axios.interceptors.request.use(
  (config): AxiosRequestConfig<any> => {
    const token = window.localStorage.getItem('token')
    if (token) {
      //@ts-ignore忽略错误

      //这里的['token']根据实际接口字段名修改
      config.headers['token'] = token
    }

    //自定义的配置，添加特殊处理，比如loading的展示或者强求回调函数


    return config
  },
  (error) => {
    return error
  }
)
// 响应拦截
axios.interceptors.response.use(
  (res) => {
    const { status, config } = res
    const { code, data, msg } = res.data

    //处理状态码异常
    if (code !== '200') {

    }

    return data
  },
  (error) => {
    const { response, message } = error
    return Promise.reject(error)
  }
)


//定义接口
interface ResType<T> {
  code: number,
  data?: T,
  msg: string,
}
interface Http {
  get<T>(url: string, params?: unknown, options?: object): Promise<ResType<T>>
  post<T>(url: string, params?: unknown, options?: object): Promise<ResType<T>>
}

//将常用请求挂载在httpp对象下，使用时http[请求类型](url,params)
const http: Http = {
  //定义get请求
  get(url, params, options) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params, ...options })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })

    })
  },
  post(url, params, options) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, JSON.stringify(params), {
          ...options
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
}

export default http